package org.itboys.weixin;

import com.google.common.collect.Maps;
import org.itboys.baseobject.entity.City;
import org.itboys.baseobject.service.CityService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.pay.weixin.WXPayService;
import org.itboys.pay.weixin.WeixinOrderQuery;
import org.itboys.pay.weixin.WeixinPaySignTool;
import org.itboys.product.entity.Order;
import org.itboys.product.entity.Product;
import org.itboys.product.service.OrderService;
import org.itboys.product.service.ProductService;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.service.WeixinConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by huml on 2016/4/19.
 * 微信订单业务
 */
@RestController
@RequestMapping("/weixin/order")
public class OrderWeixinController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CityService cityService;
    @Autowired
    private WeixinConfigService weixinConfigService;

    /**
     * 购买页面
     * @return
     */
    @RequestMapping("/buyProductVM")
    public ModelAndView buyProductVM(@RequestParam("productId")Long productId, Model model){
        Product product = productService.getById(productId);
        model.addAttribute("product", product);
        return new ModelAndView("site/buyProduct");
    }

    /**
     * 购买生成订单
     * @param name  收货人
     * @param mobile  联系电话
     * @param districtId  区县
     * @param address  详细地址
     * @param postcode  邮编
     * @param productId  产品id
     * @param payMethod  支付方式
     * @param response
     * @return
     */
    @RequestMapping("/buyProduct")
    public void buyProduct(@RequestParam("name")String name,
                                   @RequestParam("mobile")String mobile,
                                   @RequestParam("districtId")Long districtId,
                                   @RequestParam("address")String address,
                                   @RequestParam("postcode")String postcode,
                                   @RequestParam("productId")Long productId,
                                   @RequestParam("payMethod")Integer payMethod,
                                   HttpServletRequest request,
                                   HttpServletResponse response){
       try {
           FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
           City city = cityService.getById(districtId);
           address = city.getMergerName() + address;
           Order order = orderService.createOrder(member.getId(),productId,1,payMethod,address, name, mobile, postcode);
           Object object = orderService.payOrder(order.getId(), request);
           if(object instanceof Integer){//说明是能量豆支付
               AjaxUtils.renderText(response, String.valueOf(object));
           } else {
               WeixinPaySignTool weixinPaySignTool = (WeixinPaySignTool)object;
               Map<String, Object> map = Maps.newHashMapWithExpectedSize(2);
               map.put("weixinPaySignTool", weixinPaySignTool);
               map.put("order", order);
               AjaxUtils.renderJson(response, map);
           }
       } catch (Exception e) {
           logger.error("/weixin/order/buyProduct error", e);
           AjaxUtils.renderText(response, CommonConstants.FAIL);
       }
    }

    /**
     * 跳转能量豆购买页面
      * @return
     */
    @RequestMapping("/toBean")
    public ModelAndView toBean(){
        return new ModelAndView("site/productEnergyBean");
    }

    /**
     * 购买能量豆
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/buyBean")
    public void buyBean(HttpServletRequest request,
                                HttpServletResponse response){
        try {
            FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
            Order order = orderService.buyBean(member);
            Object object = orderService.payOrder(order.getId(), request);
            WeixinPaySignTool weixinPaySignTool = (WeixinPaySignTool)object;
            Map<String, Object> map = Maps.newHashMapWithExpectedSize(2);
            map.put("weixinPaySignTool", weixinPaySignTool);
            map.put("order", order);
            AjaxUtils.renderJson(response, map);
        } catch (Exception e) {
            logger.error("/weixin/order/buyBean error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 支付   能量豆的话直接支付  微信的话先下单签名
     * @param orderId
     * @param request
     * @param response
     */
    @RequestMapping("/doPay")
    public void doPay(@RequestParam("orderId")Long orderId,
                      HttpServletRequest request,
                      HttpServletResponse response){
        try {
            Object object = orderService.payOrder(orderId, request);
            if(object instanceof Integer){//说明是能量豆支付
                AjaxUtils.renderText(response, String.valueOf(object));
            } else {
                WeixinPaySignTool weixinPaySignTool = (WeixinPaySignTool)object;
                AjaxUtils.renderJson(response, weixinPaySignTool);
            }
        } catch (Exception e) {
            logger.error("/weixin/order/doPay error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 支付成功页面
     * @param orderId
     * @param model
     * @return
     */
    @RequestMapping("/paySuccess")
    public ModelAndView paySuccess(@RequestParam("orderId")Long orderId, Model model){
        model.addAttribute("order", orderService.getById(orderId));
        return new ModelAndView("site/paySuccess");
    }

    /**
     * 微信支付异步回调
     * @param request
     * @param response
     */
    @RequestMapping("/weixinNotify")
    public void weixinNotify(HttpServletRequest request, HttpServletResponse response){
        try {
            String result = orderService.weixinNotify(request);
            AjaxUtils.renderText(response, result);
        } catch (Exception e) {
            logger.error("/weixin/order/weixinNotify error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

    /**
     * 查询订单状态
     */
    @RequestMapping("/weixinOrderQuery")
    public void weixinOrderQuery(HttpServletRequest request,
                                 @RequestParam("orderNo")String orderNo,
                                 HttpServletResponse response){
        try {
            FuzionMember member = (FuzionMember) request.getSession().getAttribute("member");
            WeixinConfig weixinConfig = weixinConfigService.getById(Long.valueOf(member.getWeixinId()));
            String state = WXPayService.orderQuery(orderNo, weixinConfig.getAppId(), weixinConfig.getPartnerId(), weixinConfig.getPartnerKey());
            if(state.equals(WeixinOrderQuery.SUCCESS)){
                //支付成功
                AjaxUtils.renderText(response, CommonConstants.SUCCESS);
            } else {
                AjaxUtils.renderText(response, CommonConstants.FAIL);
            }
        } catch (Exception e) {
            logger.error("/weixin/order/weixinOrderQuery error", e);
            AjaxUtils.renderText(response, CommonConstants.FAIL);
        }
    }

}
